from rest_framework import serializers
from .models import Label, Article, Comment
from rest_framework.fields import SerializerMethodField


# 标签序列化器
class LabelSerializer(serializers.ModelSerializer):
    # 指定模型和展示字段
    class Meta:
        model = Label
        fields = '__all__'


# 文章序列化器
class ArticleSerializer(serializers.ModelSerializer):
    # 展示用户头像
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True, label='头像')
    # 展示用户姓名
    user_name = serializers.CharField(source='user.username', read_only=True, label='用户名')

    # 指定模型和展示字段
    class Meta:
        model = Article
        exclude = ['is_delete']
        extra_kwargs = {
            'page_view': {'read_only': True},
            'priority': {'read_only': True}
        }


# 一级评论序列化器
class CommentSerializer(serializers.ModelSerializer):
    # 展示用户头像
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True, label='头像')
    # 展示用户姓名
    user_name = serializers.CharField(source='user.username', read_only=True, label='用户名')
    # 额外方法增加字段
    son_count = SerializerMethodField(method_name='get_son_count', read_only=True, label='回复数')

    # 指定模型和展示字段
    class Meta:
        model = Comment
        exclude = ['is_delete']

    # 自定义方法
    def get_son_count(self, comment):
        return comment.parent_comment_set.count()


# 子级评论序列化器
class SonCommentSerializer(serializers.ModelSerializer):
    # 展示用户头像
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True, label='头像')
    # 展示用户姓名
    user_name = serializers.CharField(source='user.username', read_only=True, label='用户名')
    # 回复人
    reply_name = serializers.CharField(source='reply_comment.user.username', read_only=True, label='回复人')

    # 指定模型和展示字段
    class Meta:
        model = Comment
        exclude = ['is_delete']
